package com.salton123.ui.base

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.Toast
import androidx.asynclayoutinflater.view.AsyncLayoutInflater
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.salton123.log.XLog
import com.salton123.saltonframework.R

/**
 * User: newSalton@outlook.com
 * Date: 2019/12/11 9:29
 * ModifyTime: 9:29
 * Description:
 */
open class ComponentLife : IComponentLife {
    private var TAG = "ComponentLife"

    private lateinit var rootLayout: LinearLayout

    private lateinit var titleLayout: LinearLayout

    private lateinit var contentLayout: FrameLayout

    private lateinit var hostActivity: FragmentActivity

    private lateinit var attachHost: IComponentLife

    fun with(host: IComponentLife) {
        attachHost = host
        hostActivity = when (host) {
            is Fragment -> {
                host.requireActivity()
            }
            is FragmentActivity -> {
                host
            }
            else -> {
                throw RuntimeException("instance must Fragment or Activity")
            }
        }
        TAG = hostActivity.javaClass.simpleName
        initRootLayout()
    }

    private fun initRootLayout() {
        Log.i(TAG, "salton-initRooLayout")
        rootLayout = LinearLayout(activity()).apply {
            id = R.id.salton_id_top_layout
            orientation = LinearLayout.VERTICAL
            layoutParams = FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT
            )
        }.apply {
            contentLayout = FrameLayout(activity()).apply {
                id = R.id.salton_id_content_layout
                layoutParams = FrameLayout.LayoutParams(
                    FrameLayout.LayoutParams.MATCH_PARENT,
                    FrameLayout.LayoutParams.MATCH_PARENT
                )
            }
            addView(contentLayout)
            titleLayout = LinearLayout(activity()).apply {
                id = R.id.salton_id_title_layout
                orientation = LinearLayout.VERTICAL
                layoutParams = LinearLayout.LayoutParams(
                    FrameLayout.LayoutParams.MATCH_PARENT,
                    FrameLayout.LayoutParams.WRAP_CONTENT
                )
            }
            addView(titleLayout, 0)
        }
    }

    fun getRootView(): View {
        if (!this::rootLayout.isInitialized) {
            initRootLayout()
        }
        return rootLayout
    }

    override fun inflate(isAsync: Boolean, layoutId: Int, callback: (View?) -> Unit) {
        if (isAsync) {
            AsyncLayoutInflater(activity()).inflate(layoutId, null) { view: View?, _: Int, _: ViewGroup? ->
                callback.invoke(view)
            }
        } else {
            callback.invoke(LayoutInflater.from(activity()).inflate(layoutId, null))
        }
    }

    override fun inflateContentView(isAsync: Boolean, layoutId: Int, callback: (View?) -> Unit) {
        if (!this::rootLayout.isInitialized) {
            initRootLayout()
        }
        Log.i(TAG, "salton-inflateContentView")
        inflate(isAsync, layoutId) {
            contentLayout.addView(it)
            callback.invoke(contentLayout)
        }
    }

    override fun inflateTitleBar(isAsync: Boolean, layoutId: Int, callback: (View?) -> Unit) {
        Log.i(TAG, "salton-inflateTitleBar")
        if (titleLayout.childCount > 0) {
            callback.invoke(titleLayout)
            Log.i(TAG, "salton-inflateTitleBar childCount:${titleLayout.childCount}")
            return
        }
        inflate(isAsync, layoutId) {
            titleLayout.addView(it)
            callback.invoke(titleLayout)
        }
    }

    override fun activity(): FragmentActivity {
        return hostActivity
    }

    override fun <T : View> f(resId: Int): T {
        return rootLayout.findViewById(resId)
    }

    override fun longToast(toast: String) {
        Toast.makeText(activity(), toast, Toast.LENGTH_LONG).show()
        log(toast)
    }

    override fun shortToast(toast: String) {
        Toast.makeText(activity(), toast, Toast.LENGTH_SHORT).show()
        log(toast)
    }

    override fun log(msg: String) {
        XLog.i(javaClass, msg)
    }

    override fun openActivity(clz: Class<*>, bundle: Bundle?) {
        val intent = Intent(activity(), clz)
        bundle?.let {
            intent.putExtras(bundle)
        }
        activity().startActivity(intent)
    }

    override fun openActivityForResult(clz: Class<*>, bundle: Bundle?, requestCode: Int) {
        val intent = Intent(activity(), clz)
        bundle?.let {
            intent.putExtras(bundle)
        }
        activity().startActivityForResult(intent, requestCode)
    }

    override fun setListener(vararg ids: Int) {
        for (id in ids) {
            f<View>(id).setOnClickListener(attachHost)
        }
    }

    override fun setListener(vararg views: View) {
        for (view in views) {
            view.setOnClickListener(attachHost)
        }
    }

    override fun show(vararg views: View) {
        for (view in views) {
            view.visibility = View.VISIBLE
        }
    }

    override fun hide(vararg views: View) {
        for (view in views) {
            view.visibility = View.GONE
        }
    }

    override fun self(): IComponentLife = attachHost

    /**
     * 这里是没有用的，因为接口多出来而已
     */
    override fun onClick(v: View?) {
        println("${attachHost.javaClass.name}.onClick")
    }
}